package cn.e3mall.item.listener;

import java.io.FileWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;

import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import cn.e3mall.item.pojo.Item;
import cn.e3mall.pojo.TbItem;
import cn.e3mall.pojo.TbItemDesc;
import cn.e3mall.service.ItemService;
import freemarker.template.Configuration;
import freemarker.template.Template;

public class ItemMessageListener implements MessageListener {

	@Autowired
	private ItemService itemService;
	@Autowired
	private FreeMarkerConfigurer freeMarkerConfigurer;
	
	//商品保存路径
	@Value("${FREEMARKER_HTML_PATH}")
	private String FREEMARKER_HTML_PATH;
	
	@Override
	public void onMessage(Message message) {
		
		//准备商品详情页面的模板
		try {
			//从消息从取商品id
			TextMessage textMessage = (TextMessage) message;
			
			//获取消息
			String text = textMessage.getText();
				
			if(text == null) return; //若为空
				
			//判断操作类型
			String[] textArray = text.split("-");	//分割文本，拿到操作类型标识和商品ID
				
			String opt = textArray[0];
				
			String info = textArray[1];
				
			if(opt.equals("ADD")) {
				//转为long
				Long itemId = new Long(info);
				
				//查询商品数据和商品描述
				TbItem tbItem = itemService.getItemById(itemId);
				
				Item item = new Item(tbItem);
				
				TbItemDesc itemDesc = itemService.getItemDescById(itemId);
				
				//准备map，封装商品数据
				Map<String, Object> data = new HashMap<String,Object>();
				
				data.put("item", item);
				data.put("itemDesc", itemDesc);
				
				//创建configuration对象
				Configuration configuration = freeMarkerConfigurer.getConfiguration();
				
				//生成模板对象
				Template template = configuration.getTemplate("item.ftl");
				
				//准备字符流
				Writer out = new FileWriter(FREEMARKER_HTML_PATH+itemId+".htm");
				
				//生成文件
				template.process(data, out);
				
				//关闭流
				out.close();
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}

}
